package com.hc.springsecurity;

import com.hc.springsecurity.handler.MyAccessDeniedHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hc
 * @date 2022/1/6 15:15
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Resource
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //表单登录
                .usernameParameter("username123")
                .passwordParameter("password234")
                .loginPage("/openLogin") //设置登录页面对应的地址，默认是/login
                .loginProcessingUrl("/userLogin") //设置用户登录时请求的地址，默认是/login
                .and()
                .authorizeRequests()
                //授权
                .antMatchers("/openLogin").anonymous()//toLogin放行：不需要拦截，可以随便访问
                .antMatchers("/openIndex").permitAll()//toIndex放行：不需要拦截，可以随便访问
                .antMatchers("/**/*.css", "/**/*.js", "/imgs/**").permitAll()//放行静态资源

                //权限
                //.antMatchers("/openDemo").hasAuthority("spu:delete234")
                //.antMatchers("/openDemo").hasAnyAuthority("spu:delete234","spu:update")
                //角色
                //.antMatchers("/openDemo").hasRole("vip")
                //.antMatchers("/openDemo").hasAnyRole("vip","aa","bb")
                //白名单
                //.antMatchers("/openDemo").hasIpAddress("192.168.14.7")
                //.anyRequest().access("@myServiceImpl.hasPermission(request,authentication)")

                .anyRequest().authenticated()//其它请求都必须认证后才能访问
                .and()
                .logout()
                .logoutUrl("/userLogout")
                .logoutSuccessUrl("/openIndex")
                .and()
                // 用户没有权限的页面处理
                .exceptionHandling()
                .accessDeniedHandler(myAccessDeniedHandler)   //配置403访问错误处理器
                .and()
                //关闭防火墙：为了保证完整流程可用关闭CSRF安全协议
                .csrf().disable();
    }

}
